import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 定义类型
type GroupMemberWithUser = {
  id: string
  userId: string
  groupId: string
  role: string
  createdAt: Date
  updatedAt: Date
  user: {
    name: string | null
    email: string
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    
    if (!session?.user) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    // 只有教师和管理员可以授权学生
    if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const experimentId = params.id
    const body = await request.json()
    const { studentIds } = body

    if (!studentIds || !Array.isArray(studentIds) || studentIds.length === 0) {
      return NextResponse.json({ message: '缺少学生ID' }, { status: 400 })
    }

    // 验证实验是否存在且属于当前用户
    const experiment = await prisma.experiment.findFirst({
      where: {
        id: experimentId,
        createdById: session.user.id
      }
    })

    if (!experiment) {
      return NextResponse.json({ message: '实验不存在或无权限' }, { status: 404 })
    }

    // 验证学生是否存在
    const students = await prisma.user.findMany({
      where: {
        id: {
          in: studentIds
        },
        role: 'STUDENT'
      }
    })

    if (students.length !== studentIds.length) {
      return NextResponse.json({ message: '部分学生不存在' }, { status: 400 })
    }

    // 批量创建授权（忽略已存在的）
    const authorizations = await Promise.all(
      studentIds.map(async (studentId: string) => {
        try {
          return await prisma.experimentAuthorization.create({
            data: {
              experimentId,
              studentId
            }
          })
        } catch (error) {
          // 如果已存在，忽略错误
          return null
        }
      })
    )

    const successCount = authorizations.filter(auth => auth !== null).length

    return NextResponse.json({ 
      message: `成功授权 ${successCount} 名学生`,
      authorizations: authorizations.filter(auth => auth !== null)
    })
  } catch (error) {
    console.error('授权学生失败:', error)
    return NextResponse.json({ message: '授权学生失败' }, { status: 500 })
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    
    if (!session?.user) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    // 只有教师和管理员可以取消授权
    if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const experimentId = params.id
    const body = await request.json()
    const { studentIds } = body

    if (!studentIds || !Array.isArray(studentIds) || studentIds.length === 0) {
      return NextResponse.json({ message: '缺少学生ID' }, { status: 400 })
    }

    // 验证实验是否存在且属于当前用户
    const experiment = await prisma.experiment.findFirst({
      where: {
        id: experimentId,
        createdById: session.user.id
      }
    })

    if (!experiment) {
      return NextResponse.json({ message: '实验不存在或无权限' }, { status: 404 })
    }

    // 检查是否有学生在分组中
    const studentsInGroups = await prisma.groupMember.findMany({
      where: {
        userId: {
          in: studentIds
        },
        group: {
          experimentId
        }
      },
      include: {
        user: {
          select: {
            name: true,
            email: true
          }
        }
      }
    }) as GroupMemberWithUser[]

    if (studentsInGroups.length > 0) {
      const studentNames = studentsInGroups.map((member: GroupMemberWithUser) => 
        member.user.name || member.user.email
      ).join(', ')
      return NextResponse.json({ 
        message: `以下学生已加入分组，请先将其从分组中移除：${studentNames}` 
      }, { status: 400 })
    }

    // 删除授权
    const result = await prisma.experimentAuthorization.deleteMany({
      where: {
        experimentId,
        studentId: {
          in: studentIds
        }
      }
    })

    return NextResponse.json({ 
      message: `成功取消 ${result.count} 名学生的授权`
    })
  } catch (error) {
    console.error('取消授权失败:', error)
    return NextResponse.json({ message: '取消授权失败' }, { status: 500 })
  }
} 